package com;

import java.io.File;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.util.concurrent.ServiceManager;
import com.log.Scanner;

@Component
public class StartupRunner implements CommandLineRunner {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
   
    @Autowired
    PiwikPredictionioSysCfgDao piwikPredictionioSysCfgDao;
    @Autowired 
    Scanner scanner;
    @Resource(name="piwikProducerServiceManager")
	private ServiceManager piwikProducerServiceManager;
    @Resource(name="piwikConsumerServiceManager")
   	private ServiceManager piwikConsumerServiceManager;
	
    @Override
    @Transactional
    public void run(String... args) throws Exception {
    	
    	
    	for (String arg : args) {
			if (StringUtils.startsWith(arg, "--logUrl")) {
				File file = new File(arg.replace("--logUrl=", ""));
				if (!file.isFile()) {
					file.createNewFile();
				}
			}
			
			readMode(arg);
		}
    	
    	initPiwikPredictionioSysCfgData(PiwikPredictionioSysCfgDao.key_lastInsertedPiwikLogActionId);
    	initPiwikPredictionioSysCfgData(PiwikPredictionioSysCfgDao.key_lastInsertedPiwikLogLinkVisitActionId);
    	initPiwikPredictionioSysCfgData(PiwikPredictionioSysCfgDao.key_lastInsertedPiwikLogVisitId);
    	initPiwikPredictionioSysCfgData(PiwikPredictionioSysCfgDao.key_lastQueryPiwikLogLinkVisitActionId);
    	
    }
    
     void readMode(String arg) {
    	 if (!StringUtils.startsWith(arg, "--mode")) {
    		 return ;
		 }
    	 String mode = arg.replace("--mode=", "");
    	 switch (mode) {
		case "piwikProducer":
	    	piwikProducerServiceManager.startAsync();
	    	piwikProducerServiceManager.awaitHealthy();
			break;
		case "piwikConsumer":
			piwikConsumerServiceManager.startAsync();
			piwikProducerServiceManager.awaitHealthy();
			scanner.startAsync();
			break;
		default:
			break;
		}
		
	 }

	void initPiwikPredictionioSysCfgData(String key){
    	PiwikPredictionioSysCfg piwikPredictionioSysCfg = 
    			piwikPredictionioSysCfgDao.findOne(key);
    	if (piwikPredictionioSysCfg == null) {
    		 piwikPredictionioSysCfg = new PiwikPredictionioSysCfg();
    		 piwikPredictionioSysCfg.setKey(key);
    		 piwikPredictionioSysCfg.setValue("0");
    		 piwikPredictionioSysCfgDao.save(piwikPredictionioSysCfg);
		}
    	
    }
    
}